<?php

/**
 * Created by Sublime.
 * User: tchenym
 * Date: 2018/08/21
 * Time: 上午午10:25
 */
class Customer_model extends CI_Model
{

    public function __construct()
    {
        $this->load->database();
        $this->load->helper("common");
    }

    //根据session_key获取用户user_id
    public function sessionKeyToUserId($session_key)
    {
        $where   = array('session_key' => $session_key);
        $user_id = $this->db->where($where)->from('app_user')->get()->row_array()['id'];
        if ($user_id) {
            return $user_id;
        } else {
            send_json(array('code' => 4004, 'data' => '', 'msg' => "用户不存在"));
        }
    }

    //获取客户端用户第一次注册的店铺id
    public function customerFirstRegShopId($session_key)
    {
        $user_id = $this->sessionKeyToUserId($session_key);
        $where   = array('user_id' => $user_id);
        $shop_id = $this->db->where($where)->from('app_shop_user')->get()->row_array()['shop_id'];
        if ($shop_id) {
            return $shop_id;
        } else {
            send_json(array('code' => 4004, 'data' => '', 'msg' => "店铺不存在"));
        }
    }

    //绑定第一次注册的商户
    public function bindingCustomerStore($shop_id, $session_key)
    {
        $row = $this->isBinding($session_key);
        if ($row) {
            send_json(array('code' => 4004, 'data' => '', 'msg' => "已绑定商户"));
        } else {
            $user_id               = $this->sessionKeyToUserId($session_key);
            $dataArr               = array();
            $dataArr['user_id']    = $user_id;
            $dataArr['shop_id']    = $shop_id;
            $dataArr['created_at'] = date("Y-m-d H:i:s", time());
            $res                   = $this->db->insert('app_shop_user', $dataArr);
            if ($res) {
                return true;
            } else {
                return false;
            }
        }
    }

    //判断客户是否绑定商户
    public function isBinding($session_key)
    {
        $user_id = $this->sessionKeyToUserId($session_key);
        $where   = array('user_id' => $user_id);
        $row     = $this->db->where($where)->from('app_shop_user')->get()->row_array();
        if ($row) {
            return true;
        } else {
            return false;
        }
    }
}
